<template>
  <div class="product-container">
    <div class="header">
      <h1>商品列表</h1>
      <div class="header-buttons">
        <el-button type="warning" @click="refreshCache" :loading="cacheLoading">
          <el-icon><Delete /></el-icon> 刷新缓存
        </el-button>
        <el-button type="success" @click="showAddDialog">
          <el-icon><Plus /></el-icon> 添加商品
        </el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="products" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="price" label="价格" width="120">
        <template #default="scope"> ¥ {{ scope.row.price.toFixed(2) }} </template>
      </el-table-column>
      <el-table-column prop="cid" label="分类ID" width="100" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="productForm" :rules="productRules" ref="productFormRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="分类ID" prop="cid">
          <el-input-number v-model="productForm.cid" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
  getProducts,
  addProduct,
  updateProduct,
  deleteProduct,
  refreshProductCache,
  type Product,
} from '../api/product'

const loading = ref(false)
const cacheLoading = ref(false)
const submitLoading = ref(false)
const products = ref<Product[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const productFormRef = ref()

const productForm = reactive<Product>({
  name: '',
  price: 0,
  cid: 1,
})

const productRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  cid: [{ required: true, message: '请选择分类', trigger: 'change' }],
}

const dialogTitle = computed(() => (isEdit.value ? '编辑商品' : '添加商品'))

onMounted(() => {
  fetchProducts()
})

const fetchProducts = async () => {
  loading.value = true
  try {
    const res = await getProducts()
    if (res.data) {
      products.value = res.data
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const refreshCache = async () => {
  cacheLoading.value = true
  try {
    await refreshProductCache()
    ElMessage.success('缓存已成功刷新')
    // 刷新缓存后重新获取商品列表
    await fetchProducts()
  } catch (error) {
    console.error('刷新缓存失败:', error)
    ElMessage.error('刷新缓存失败')
  } finally {
    cacheLoading.value = false
  }
}

const resetForm = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
  productForm.id = undefined
  productForm.name = ''
  productForm.price = 0
  productForm.cid = 1
}

const showAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: Product) => {
  isEdit.value = true
  resetForm()

  // 复制数据到表单
  Object.assign(productForm, row)
  dialogVisible.value = true
}

const handleDelete = (row: Product) => {
  ElMessageBox.confirm(`确定要删除商品 "${row.name}" 吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        if (row.id) {
          await deleteProduct(row.id)
          ElMessage.success('删除成功')
          fetchProducts()
        }
      } catch (error) {
        console.error('删除商品失败:', error)
        ElMessage.error('删除商品失败')
      }
    })
    .catch(() => {})
}

const submitForm = async () => {
  if (!productFormRef.value) return

  await productFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          await updateProduct(productForm)
          ElMessage.success('更新成功')
        } else {
          await addProduct(productForm)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchProducts()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}
</style>
